package servlets.message;

import hibernate.method.MessageMethods;
import hibernate.method.UserMethods;
import hibernate.model.Message;
import hibernate.model.User;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class MessageDetails
 */
@WebServlet("/MessageDetails")
public class MessageDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MessageDetails() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String req = request.getParameter("messageID");
		int messageID = Integer.parseInt(req);
		response.setContentType("text/plain");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session s = sessionFactory.openSession();
		s.beginTransaction();
		MessageMethods msg_m = new MessageMethods();
		UserMethods u_m = new UserMethods();
		Message m = msg_m.id_to_msg(sessionFactory, s, messageID);
		msg_m.receive(sessionFactory, s, m);
		User sender_user = u_m.id_to_user(sessionFactory, s, m.getSender_id());
		String sender = sender_user.getUsername();
		User receiver_user = u_m.id_to_user(sessionFactory, s, m.getReceiver_id());
		String receiver = receiver_user.getUsername();
		
		JSONObject json = new JSONObject();
		PrintWriter out = response.getWriter();
		try {
			json.put("message_id", m.getMessage_id());
			json.put("sender", sender);
			json.put("receiver", receiver);
			json.put("sender_id", sender_user.getUser_id());
			json.put("receiver_id", receiver_user.getUser_id());
			json.put("date", m.getSend_date());
			json.put("time", m.getSend_time());
			json.put("subject", m.getSubject());
			json.put("content", m.getContent());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		out.println(json);
		out.flush();

		s.getTransaction().commit();
	}

}
